package edu.sctu.boot.admin.generator.vue;

import lombok.Data;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.*;
import java.util.Map;

import static edu.sctu.boot.admin.generator.utils.FileUtils.ensurePath;

@Data
public class BaseGenerator {

    private VelocityEngine ve;
    private VelocityContext ctx;
    private Template template;

    public BaseGenerator() {
        this.ve = new VelocityEngine();
        this.ve.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        this.ve.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        this.ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        this.ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        this.ve.init();

        this.ctx = new VelocityContext();

    }

    void generate(String templateFile, String outputFile, Map<String, Object> data) throws IOException {
        ensurePath(outputFile);

        for (Map.Entry<String, Object> entry : data.entrySet()) {
            this.ctx.put(entry.getKey(), entry.getValue());
        }

        this.template = this.ve.getTemplate(templateFile);

        BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
        this.template.merge(this.ctx, writer);
        writer.flush();
        writer.close();
    }


}
